package com.bountytask.controller;

import com.alibaba.fastjson.JSONObject;
import com.bountytask.config.ScheduledTasks;
import com.bountytask.entity.ImageAndId;
import com.bountytask.service.ProveImageService;
import com.bountytask.service.impl.ProveImageServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

@Slf4j
@RestController
public class ProveImageController {
    @Autowired
    private ProveImageService proveImageService;

    @Autowired
    private ScheduledTasks scheduledTasks;

    @Value("${uploadPathImg}")
    private String uploadPathImg;

//    //提交证明图片
//    @PostMapping("/prove/submit")
//    public JSONObject proveSubmit(@RequestBody JSONObject recData){
//        return proveImageService.addImage(
//                recData.getLong("userid"),recData.getLong("taskid"),recData.getString("s"));
//    }

    /**
     * 删除某个证明图片
     * @return
     */
    @DeleteMapping("/prove/del/{id}")
    public JSONObject delProve(@PathVariable long id){
        int flag=proveImageService.deleteProve(id);
        JSONObject jsonObject=new JSONObject(true);
        if (flag==400){
            jsonObject.put("code",flag);
            jsonObject.put("message","失败");
            return jsonObject;
        }
        jsonObject.put("code",flag);
        jsonObject.put("message","成功");
        return jsonObject;
    }
    /**
     * 查找该用户在该任务中提交的证明图片
     * @param userid
     * @param taskid
     * @return
     */
    @GetMapping("/prove/mget/{userid}/{taskid}")
    public JSONObject selectImage(@PathVariable ("userid") long userid,@PathVariable ("taskid") long taskid){
        List<ImageAndId> list=proveImageService.selectImage(userid,taskid);
        JSONObject jsonObject=new JSONObject(true);
            jsonObject.put("code",200);
            jsonObject.put("message","成功");
            jsonObject.put("data",list.toArray());
            return jsonObject;
    }

    /**
     * 批量删除证明图片
     * @param recData
     * @return
     */
    @DeleteMapping("/prove/_mdelete")
    public JSONObject _mDelete(@RequestBody JSONObject recData){
        JSONObject jsonObject=new JSONObject(true);
        log.info(recData.getJSONArray("ids").toString());
        if(proveImageService._mDelete(recData.getJSONArray("ids"))==400)
        {
            jsonObject.put("code",400);
            jsonObject.put("message","失败");
            jsonObject.put("data","前端传的的数据不对");
        }else
        {
            jsonObject.put("code",200);
            jsonObject.put("message","成功");
        }
        return jsonObject;
    }

    //提交证明图片
    @PostMapping("/prove/submit")
    public JSONObject proveSubmit(@RequestParam("image") MultipartFile file,
                                  @RequestParam("userid") long userId,
                                  @RequestParam("taskid") long taskId) throws IOException, URISyntaxException {
        //检测图片
        if (scheduledTasks.getAccessToken()==null);
            scheduledTasks.getAccessTokenUrl();
        String RequestUrl = "https://api.weixin.qq.com/wxa/img_sec_check?access_token=" + scheduledTasks.getAccessToken();
        URL url1 = new URL(RequestUrl);
        URI RequestUri = new URI(url1.getProtocol(), url1.getHost(), url1.getPath(), url1.getQuery(), null);
        HttpClient httpclient = HttpClients.createDefault();
        HttpPost request = new HttpPost(RequestUri);
        request.addHeader("Content-Type", "application/octet-stream");
        MultipartFile checkFile = file;
        InputStream inputStream = checkFile.getInputStream();
        try {
            //创建一个byte数组，和输入的文件输入流大小一样
            byte[] byt = new byte[inputStream.available()];
            //从输入流中读取全部，并将其存储在缓冲区数组byt 中。
            inputStream.read(byt);
            //定制提交内容
            request.setEntity(new ByteArrayEntity(byt, ContentType.create("image/jpg")));
            HttpResponse response = httpclient.execute(request);
            // 从响应模型中获取响应实体
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");// 转成string
            //打印校验结果
            JSONObject object = JSONObject.parseObject(result);
            if (object.getInteger("errcode")!=0)
                file=null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(inputStream != null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        long flag=-1;
        try {
            if (file!=null){
                String fileName = System.currentTimeMillis() + file.getOriginalFilename();
                String upload_file_dir=uploadPathImg;//注意这里需要添加目录信息
                String destFileName =  uploadPathImg +fileName;
                File upload_file_dir_file = new File(upload_file_dir);
                if (!upload_file_dir_file.exists())
                {
                    upload_file_dir_file.mkdirs();
                }
                //5.把浏览器上传的文件复制到希望的位置
                File targetFile = new File(upload_file_dir_file, fileName);
                file.transferTo(targetFile);
                String url="uploadeview/"+fileName;
                flag=proveImageService.addImage(userId,taskId,url);
            }
       }catch (IOException e){
           e.printStackTrace();
        }
        JSONObject resultJson = new JSONObject(true);
        if (flag==-1){
            resultJson.put("code",400);
            resultJson.put("message","失败");
            return resultJson;
        }
        resultJson.put("code",200);
        resultJson.put("message","成功");
        JSONObject data = new JSONObject();
        data.put("id",flag);
        resultJson.put("data",data);
        return resultJson;
    }
}
